package bigbrother.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import bigbrother.entity.Employee;
import bigbrother.service.EmployeeService;
import bigbrother.service.IEmployeeService;

/**
 * Servlet implementation class HireServlet
 */
@WebServlet("/hire")
public class HireServlet extends HttpServlet {
	Logger logger 
	= LogManager.getLogger(HireServlet.class);
	
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HireServlet() {
		super();
		// TODO Auto-generated constructor stub
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		IEmployeeService service = EmployeeService.getService();
		String message = null;
		if(service.canUseId(id)){
			message =  "사용할 수 있는 ID 입니다.";
		}else{
			message = "이미 사용중인 ID 입니다.";
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println(message);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String pass = request.getParameter("pass");

		IEmployeeService service = EmployeeService.getService();
		Employee emp = new Employee(id, name, pass);
		String path = null;
		try {
			service.hireEmployee(emp);
			path = "hiresuccess.jsp";
		} catch (Exception e) {
			request.setAttribute(
					"javax.servlet.jsp.jspException", e);
			path = "errorpage.jsp";
			logger.error(e.getMessage());
		}finally{
			RequestDispatcher dispatcher 
			= request.getRequestDispatcher(path);
			dispatcher.forward(request, response);
		}

	}

}
